package com.logic.system.config.wsdl;

import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.ws.transport.http.HttpComponentsMessageSender;

import com.logic.system.remote.WriteBackStatusClient;

/**
 * Author: omer 
 * Date  : 02-03-2016
 */
@Configuration
public class WSDLConfiguration implements EnvironmentAware {

    private static final String ENV_WSDL = "logic.wsdl.";
    private static RelaxedPropertyResolver wsdlPropertyResolver;

    private static final String PROP_WSDL_SERVICE_URL = "service-url";
    private static final String PROP_WSDL_CONTEXT_PACKAGE = "context-package";

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        String contextPackage = wsdlPropertyResolver.getProperty(PROP_WSDL_CONTEXT_PACKAGE, String.class, "");
        marshaller.setContextPath(contextPackage);
        return marshaller;
    }

    @Bean
    public HttpComponentsMessageSender messageSender(){
        HttpComponentsMessageSender messageSender = new HttpComponentsMessageSender();
        messageSender.setConnectionTimeout(30000);
        messageSender.setReadTimeout(30000);

        return messageSender;
    }

    @Bean
    public WriteBackStatusClient writeBackStatusClient(Jaxb2Marshaller marshaller) {
        WriteBackStatusClient client = new WriteBackStatusClient();
        String serviceUrl = wsdlPropertyResolver.getProperty(PROP_WSDL_SERVICE_URL, String.class, "");
        client.setDefaultUri(serviceUrl);
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);
        client.setMessageSender(messageSender());

        return client;
    }

    @Override
    public void setEnvironment(Environment environment) {
        wsdlPropertyResolver = new RelaxedPropertyResolver(environment, ENV_WSDL);
    }
}
